using UnityEngine;
using System.Collections;

/// \class  gkPowerGaugeController
/// \brief  The controller of the submarine power gauge
[AddComponentMenu("GK/Engine/Game/Power/gkPowerGaugeController")]
public class gkPowerGaugeController : MonoBehaviour 
{	
	/// The power drawn change max (in one second)
	public float DrawnPowerChangeMax = 0.5f;
	
	/// The power component
	private gkPowerComponent m_rPowerComponent;
	
	/// The last drawn power
	private float m_fDrawnPower;
	
	/// \brief  Called just after the game begin to play
	void Start()
	{
		// Grab the power component of the hierarchy the gauge is on
		m_rPowerComponent = transform.root.GetComponentInChildren<gkPowerComponent>();
	}
	
	/// \brief  Called each frame
	void LateUpdate()
	{
		// Update the drawn power taking into account the interpolation inertia
		UpdateDrawnPower();
		// Draw the interpolated power gauge percentage
		DrawPower();
	}
	
	/// \brief  Draw the power
	void DrawPower()
	{
		// Set the material progress parameter accordingly to the power percentage
		renderer.material.SetFloat("_Progress", m_fDrawnPower);
	}
		
		/// \brief  Update the draw power
	void UpdateDrawnPower()
	{
		float fRealPower;
		float fDrawnPowerChange;
		float fDrawnPowerChangeMax;
	
		// Get the real power
		fRealPower = m_rPowerComponent.GetPowerPercentage();
		
		// Compute the needed power change
		fDrawnPowerChange = fRealPower - m_fDrawnPower;
	
		// Clamp the drawn power if needed
		fDrawnPowerChangeMax = DrawnPowerChangeMax * Time.deltaTime;
		if(fDrawnPowerChange > fDrawnPowerChangeMax)
		{
			fDrawnPowerChange = fDrawnPowerChangeMax;
		}
		else if(fDrawnPowerChange < -fDrawnPowerChangeMax)
		{
			fDrawnPowerChange = -fDrawnPowerChangeMax;
		}
	
		// Apply the power change
		m_fDrawnPower += fDrawnPowerChange;
	}
}